<?php
/**
 * Medical Centers Overviews View
 * Display all MS Centers.
 *
 * @author Xavier VILAIN
 * @package Nawa\MedicalCenter
 * @license
 * 
 */
use Nawa\MedicalStudy\MedicalCenter;
use Fox\Msg;
use Fox\Message;
use Nawa\MedicalStudy;
use Fox\Generator;
use Fox\Html\Screen;
$xview = Xview::instance();
$ms = $xview->component('medicalstudies','object',array('msid' => $xview->val('msid')));

$data = null;
$msCenterCount = 0;
foreach($ms->medicalCentersPartners() as $medicalCenter)
{
	$data['gMedicalCentersPartners'][] = array_merge($medicalCenter->getData(),
	$medicalCenter->medicalCenter()->getData());
	$medicalCenters[$medicalCenter->mcid] = $medicalCenter;
	$msCenterCount++;
}
$screen = new Screen('sCenters','update');
$screen->pageTitle(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::LABEL_MEDICAL_CENTERS));

// Display Centers List @TODO add detail
$bMC =  $xview->module(Generator::url('medicalstudies','medicalcenters'));
$grid = $bMC->item('gMedicalCentersPartners');
$screen->add($grid);
$screen->initialize($data);
if($screen->submitted()) {

	$fields = $screen->get();
	if(!$screen->errors())
	{
		try {
			// Attach Medical Center Partner
			if(is_array($fields['gMedicalCentersPartners']))
			{
				$msCenterCount = count($fields['gMedicalCentersPartners']);
				foreach($fields['gMedicalCentersPartners'] as $partnerData)
				{
					if(!isset($partnerData['mcid'])) {
						continue;
					}
					
					$id = $partnerData['mcid'];
					unset($partnerData['msid']);
					if(isset($medicalCenters[$id])) {
						$partner = $medicalCenters[$id];
						unset($medicalCenters[$id]);
					}
					else
					{
						$partner = new MedicalCenter();
					}
					$partnerData['role'] = MedicalStudy::ROLE_MEDICAL_CENTERS;
					$partner->setFields($partnerData);
					$ms->replaceMedicalCentersPartners($partner);
				}

			}
		
			if(isset($medicalCenters) && is_array($medicalCenters))
			{
				//@TODO add a Check before deletion
				foreach($medicalCenters as $partner)
				{
					$ms->deleteFromMedicalCentersPartners($partner);
				}
			}
			$ms->prepareUpdate(MedicalStudy::CHANGE_DEFAULT);

			if($ms->update())
			{
				Message::Success(Msg(Msg::BUNDLE,Msg::MSG_UPDATE,$ms->reference));
			}
			else
			{
				Message::Information(Msg(Msg::BUNDLE,Msg::MSG_NO_UPDATE,$ms->reference));
			}
			$msCenterCount = count($ms->medicalCentersPartners());
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Message::Error($e);
		}
	}
	
}
// Bread Crumb
$crumbs = Xview::instance()->component(
	'medicalstudies',
	'breadcrumb',
	array('deepness' => 2,
		  'customerid' => $ms->customer()->getId(),
		  'customer_name' => $ms->customer()->name1,
		  'msReference' => $ms->reference,
		  'msid' => $ms->getId(),
		  'msCenterCount' => $msCenterCount)
);
$screen->breadcrumb()->crumbs($crumbs);
echo $screen->display();